from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from django.db.models import Q
from .models import TaskBlock
from .serializers import (
    TaskBlockSerializer, 
    TaskBlockCreateSerializer
)
from equipment.models import Equipment


class TaskBlockViewSet(viewsets.ModelViewSet):
    """
    任务块视图集
    """
    queryset = TaskBlock.objects.all().select_related('required_device').order_by('id')
    serializer_class = TaskBlockSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ['status', 'required_device']
    ordering = ['id']  # 默认按ID升序排列
    ordering_fields = ['id', 'created_at', 'task_name']  # 允许前端指定排序字段
    
    def get_serializer_class(self):
        if self.action in ['create', 'update', 'partial_update']:
            return TaskBlockCreateSerializer
        return TaskBlockSerializer
    
    def list(self, request, *args, **kwargs):
        """
        重写list方法，确保按ID排序返回
        """
        queryset = self.filter_queryset(self.get_queryset())
        print(f"返回任务块数量: {queryset.count()}")
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    

    @action(detail=False, methods=['get'])
    def available_devices(self, request):
        """
        获取可用设备列表
        """
        devices = Equipment.objects.all()
        device_data = [{
            'id': device.id,
            'device_name': device.device_name,
            'organization': device.organization,
            'device_quantity': device.device_quantity,
            'device_capacity': device.device_capacity
        } for device in devices]
        
        return Response(device_data)
